package com.dog.basics.netty.business.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dog.basics.bean.model.mtkj.MtDeviceLockPass;
import com.dog.basics.common.util.RedisUtil;
import com.dog.basics.common.util.SpringContextUtils;
import com.dog.basics.netty.business.IBusinessServer;
import com.dog.basics.netty.protobuf.dto.DogNewsContentDto;
import com.dog.basics.netty.util.SessionSocketHolder;
import com.dog.basics.security.util.SecurityUtils;
import com.dog.basics.service.mtkj.IMtDeviceLockPassService;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.log4j.Log4j2;

import java.util.List;

/**
 * @description: 开锁测试 - 业务
 * @author: He
 * @date: Created in 2020/10/13 14:08
 * @version: 1.0
 * @modified By:
 */
@Log4j2
public class ResponseHandlerImplUnlockingTest implements IBusinessServer<DogNewsContentDto.Message> {

    /**
     * 开锁测试按钮回应 - 执行
     *
     * @param ctx
     * @param msg
     * @throws InterruptedException guonh 2020年10月13日
     */
    @Override
    public void businessHandler(ChannelHandlerContext ctx, DogNewsContentDto.Message msg) throws InterruptedException {
        log.info("开锁测试按钮回应:{}", msg.toString());
        // 查询设备标识
        Long dvId = SessionSocketHolder.getSession(ctx.channel().id().asLongText());
        //解除绑定
        List<MtDeviceLockPass> list = SpringContextUtils.getBean(IMtDeviceLockPassService.class).list(Wrappers.<MtDeviceLockPass>lambdaQuery().eq(MtDeviceLockPass::getLockId, dvId).eq(MtDeviceLockPass::getPassNum, msg.getLockport()).orderByDesc(MtDeviceLockPass::getCreateTime).last("limit 1"));
        if (CollUtil.isNotEmpty(list)) {
            MtDeviceLockPass mtDeviceLockPass = list.get(0);
            mtDeviceLockPass.setWheeId(-1L);
            mtDeviceLockPass.setPassStatus(0);
            mtDeviceLockPass.setPassLockStatus(0);
            mtDeviceLockPass.setUpdateTime(DateUtil.currentSeconds());
        //    mtDeviceLockPass.setUpdateBy(SecurityUtils.getSysUser().getUserId());
            SpringContextUtils.getBean(IMtDeviceLockPassService.class).updateById(mtDeviceLockPass);
        }

        // 声明redis 中的存储key
        String receivedKey = StrUtil.format("SEND-COMMAND:STATE:{}:{}", dvId, msg.getMsgType());
        // 存储应答结果
        RedisUtil.set(receivedKey, Validator.equal(msg.getMsgCode(), 1) ? Boolean.TRUE : Boolean.FALSE, 45);
    }
}
